package cn.dansj.common.utils.transfer;

import java.util.Random;

/**
 * 六十二进制转换工具类
 */
public abstract class Base62Converter {

    // 将字符集打乱就会带有一点加密效果
    private static final String chars = "W01FagxAI3ZoDkdc4CuN8zBrn5slPTMQ7UKeHpiOv9hjSRwGq6VYymfEJt2LbX";

    private static final int scale = 62;

    public static String shuffleString(String input) {
        char[] chars = input.toCharArray();
        Random random = new Random();

        for (int i = 0; i < chars.length; i++) {
            int index = random.nextInt(chars.length - i) + i;
            // Swap the current character with the random character
            char temp = chars[index];
            chars[index] = chars[i];
            chars[i] = temp;
        }

        return new String(chars);
    }

    /**
     * 将数字转为62进制
     *
     * @param num Long 型数字
     * @return 62进制字符串
     */
    public static String encode(long num) {
        StringBuilder sb = new StringBuilder();
        int remainder;

        while (num > scale - 1) {
            remainder = Long.valueOf(num % scale).intValue();
            sb.append(chars.charAt(remainder));
            num = num / scale;
        }

        sb.append(chars.charAt(Long.valueOf(num).intValue()));
        return sb.reverse().toString();
    }

    /**
     * 62进制字符串转为数字
     *
     * @param str 编码后的62进制字符串
     * @return 解码后的 10 进制字符串
     */
    public static long decode(String str) {
        long num = 0;
        int index;
        for (int i = 0; i < str.length(); i++) {
            index = chars.indexOf(str.charAt(i));
            num += (long) (index * (Math.pow(scale, str.length() - i - 1)));
        }
        return num;
    }

}